package com.junlong0716.enjoylearning.ui

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.KnowledgeTypeAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.ClassifyEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.getknowledgedemo.decoration.DividerItemNoEndDecoration
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.activity_add_type.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class AddTypeActivity : AppCompatActivity() {

    private lateinit var knowledgeTypeAdapter: KnowledgeTypeAdapter
    private lateinit var typeData: ArrayList<ClassifyEntity.DetailsBean>
    private lateinit var typesData: ArrayList<ClassifyEntity.DetailsBean>
    private var mSelectedTypes: ArrayList<ClassifyEntity.DetailsBean>? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_type)

        try {
            val bundle = intent.extras
            mSelectedTypes = bundle.getSerializable("HAS_SELECTED_TYPES") as ArrayList<ClassifyEntity.DetailsBean>
        } catch (e: Exception) {
            Logger.d("首次加载~")
        }

        requestClassify()

        rl_back.setOnClickListener { finish() }
        tv_title.text = "选择分类"
        typeData = ArrayList()

        rv_type.layoutManager = LinearLayoutManager(this)
        knowledgeTypeAdapter = KnowledgeTypeAdapter(typeData, R.layout.item_type)

        rv_type.adapter = knowledgeTypeAdapter
        rv_type.addItemDecoration(DividerItemNoEndDecoration(this, DividerItemNoEndDecoration.VERTICAL_LIST, 5, ContextCompat.getColor(this, R.color.recyclerview_divider_gray)))
        knowledgeTypeAdapter.setOnItemClickListener { adapter, view, position ->
            typeData[position].selected = !typeData[position].selected
            adapter.notifyItemChanged(position)
        }

        bt_confirm.setOnClickListener {
            typesData = ArrayList()

            for (i in 0 until typeData.size) {
                if (typeData[i].selected) {
                    typesData.add(ClassifyEntity.DetailsBean(typeData[i].id, typeData[i].classifyName, false))
                }
            }

            val intent = Intent()
            val bundle = Bundle()
            bundle.putSerializable("KNOWLEDGE_TYPES", typesData)
            intent.putExtras(bundle)
            setResult(0, intent)
            finish()
        }

    }

    private fun requestClassify() {
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_CLASSIFY)
                .tag(this)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .cacheKey("CATCH_CLASSIFY")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        setData(response!!.body())
                    }

                    override fun onCacheSuccess(response: Response<String>?) {
                        setData(response!!.body())
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("请求失败！")
                    }
                })
    }

    private fun setData(body: String?) {
        val jsonObject = JSONObject(body)
        val data = jsonObject.getJSONArray("data")
        val classifyData = ArrayList<ClassifyEntity>()
        val itemArray = ArrayList<ClassifyEntity.DetailsBean>()
        for (i in 0 until data.length()) {
            val id = data.getJSONObject(i).getInt("id")
            val classifyName = data.getJSONObject(i).getString("classifyName")
            val details = data.getJSONObject(i).getJSONArray("details")
            for (j in 0 until details.length()) {
                val id = details.getJSONObject(j).getInt("id")
                val classifyName = details.getJSONObject(j).getString("classifyName")
                itemArray.add(ClassifyEntity.DetailsBean(id, classifyName, false))
            }
            classifyData.add(ClassifyEntity(id, classifyName, itemArray))
        }

        typeData.addAll(itemArray)


        if (mSelectedTypes != null) {
            for (i in 0 until itemArray.size) {
                for (j in 0 until mSelectedTypes!!.size) {
                    if (itemArray[i].id == mSelectedTypes!![j].id) {
                        itemArray[i].selected = true
                    }
                }
            }
        }

        knowledgeTypeAdapter.notifyDataSetChanged()
    }
}
